use leptos::prelude::*;
use shq_common::prelude::{
     options::Options, Column, ColumnCell, Deptment, DpidUser, KvItem, MenuItem, Permission, Role, TreeNode,CreditReportAbnormal,TransactionAbnormal
};
use std::{collections::HashMap, fmt::Debug, vec};
#[derive(Clone, PartialEq, Eq, Debug)]
pub(super) struct TreeItem {
    id: String,
    label: String,
    parent_id: Option<String>,
    children: Vec<String>, // 只存储子节点ID
    permission: Option<Permission>,
}
impl TreeItem {
    pub(super) fn new(
        id: impl AsRef<str>,
        label: impl AsRef<str>,
        parent_id: Option<String>,
        children: Vec<String>,
        permission: Option<Permission>,
    ) -> Self {
        Self {
            id: id.as_ref().to_owned(),
            label: label.as_ref().to_owned(),
            parent_id,
            children,
            permission,
        }
    }
    pub(super) fn get_label(&self) -> &str {
        &self.label
    }
    pub(super) fn get_id(&self) -> &str {
        &self.id
    }
    pub(super) fn get_parent_id(&self) -> Option<&str> {
        self.parent_id.as_deref()
    }
    pub(super) fn get_children(&self) -> &[String] {
        self.children.as_slice()
    }
    pub(super) fn is_leaf(&self) -> bool {
        self.children.is_empty()
    }
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct TreeItems {
    items: Vec<TreeItem>,
    not_shows: RwSignal<Vec<String>>,
}
impl Default for TreeItems {
    fn default() -> Self {
        Self {
            items: vec![],
            not_shows: RwSignal::new(vec![]),
        }
    }
}
impl TreeItems {
    pub fn from_options(opts: &Options) -> Self {
        match opts {
            Options::Array(items) => items.into(),
            Options::Map(kv_items) => kv_items.into(),
            Options::Tree(tree_nodes) => tree_nodes.into(),
            Options::Fetch(_fetch_params) => TreeItems::default(),
        }
    }
    pub fn from_items(items: Vec<TreeItem>, not_shows: Vec<String>) -> Self {
        Self {
            items,
            not_shows: RwSignal::new(not_shows),
        }
    }
    pub fn from_column_cells(cols: &Vec<ColumnCell>, not_shows: Vec<String>) -> Self {
        let mut opts: Vec<TreeItem> = Vec::new();
        add_col_cells(cols, None, &mut opts);
        Self {
            items: opts,
            not_shows: RwSignal::new(not_shows),
        }
    }
    pub fn to_items(&self) -> &[TreeItem] {
        &self.items.as_slice()
    }
    pub fn filter_trees(&self, filter_text: &str) -> Vec<&TreeItem> {
        if filter_text.is_empty() {
            return self.items.iter().collect();
        }
        return self
            .items
            .iter()
            .filter(|item| item.label.contains(filter_text))
            .collect();
    }
    pub fn set_not_shows(&self, not_shows: Vec<String>) {
        self.not_shows.set(not_shows);
    }
    pub(crate) fn get_label(&self, id: &str) -> Option<&str> {
        self.items
            .iter()
            .find(|i| i.id == id)
            .map(|i| i.get_label())
    }
}
impl From<&Vec<TreeNode>> for TreeItems {
    fn from(node: &Vec<TreeNode>) -> Self {
        let mut items: Vec<TreeItem> = Vec::new();
        for n in node.iter() {
            let children: Vec<String> = node
                .iter()
                .filter(|c| c.parent_key.as_deref() == Some(n.key.as_str()))
                .map(|c| c.key.to_owned())
                .collect();
            items.push(TreeItem::new(
                n.key.clone(),
                n.title.clone(),
                n.parent_key.clone(),
                children,
                None,
            ));
        }
        Self {
            items,
            not_shows: RwSignal::new(vec![]),
        }
    }
}
impl From<&Vec<Column>> for TreeItems {
    fn from(cols: &Vec<Column>) -> Self {
        let mut opts: Vec<TreeItem> = Vec::new();
        add_cols(cols, None, &mut opts);
        Self {
            items: opts,
            not_shows: RwSignal::new(vec![]),
        }
    }
}
impl From<Vec<MenuItem>> for TreeItems {
    fn from(items: Vec<MenuItem>) -> Self {
        let mut opts: Vec<TreeItem> = Vec::new();
        add_menus(items, None, &mut opts);
        Self {
            items: opts,
            not_shows: RwSignal::new(vec![]),
        }
    }
}
impl From<&Vec<String>> for TreeItems {
    fn from(items: &Vec<String>) -> Self {
        let opts: Vec<TreeItem> = items
            .iter()
            .map(|item| TreeItem::new(item.clone(), item.clone(), None, vec![], None))
            .collect();
        Self {
            items: opts,
            not_shows: RwSignal::new(vec![]),
        }
    }
}
impl From<&Vec<KvItem>> for TreeItems {
    fn from(items: &Vec<KvItem>) -> Self {
        let opts: Vec<TreeItem> = items
            .iter()
            .map(|item| TreeItem::new(item.value.clone(), item.label.clone(), None, vec![], None))
            .collect();
        Self {
            items: opts,
            not_shows: RwSignal::new(vec![]),
        }
    }
}
impl From<Vec<Role>> for TreeItems {
    fn from(items: Vec<Role>) -> Self {
        let opts: Vec<TreeItem> = items
            .into_iter()
            .map(|item| TreeItem::new(item.id.to_string(), item.name, None, vec![], None))
            .collect();
        Self {
            items: opts,
            not_shows: RwSignal::new(vec![]),
        }
    }
}

impl From<Vec<DpidUser>> for TreeItems {
    fn from(items: Vec<DpidUser>) -> Self {
        let opts: Vec<TreeItem> = items
            .into_iter()
            .map(|item| TreeItem::new(item.emid.to_string(), item.name, None, vec![], None))
            .collect();
        Self {
            items: opts,
            not_shows: RwSignal::new(vec![]),
        }
    }
}

impl From<Vec<CreditReportAbnormal>> for TreeItems {
    fn from(items: Vec<CreditReportAbnormal>) -> Self {
        let opts: Vec<TreeItem> = items
            .into_iter()
            .map(|item| TreeItem::new(item.id.to_string(), item.name, None, vec![], None))
            .collect();
        Self {
            items: opts,
            not_shows: RwSignal::new(vec![]),
        }
    }
}

impl From<Vec<TransactionAbnormal>> for TreeItems {
    fn from(items: Vec<TransactionAbnormal>) -> Self {
        let opts: Vec<TreeItem> = items
            .into_iter()
            .map(|item| TreeItem::new(item.id.to_string(), item.name, None, vec![], None))
            .collect();
        Self {
            items: opts,
            not_shows: RwSignal::new(vec![]),
        }
    }
}

impl From<Vec<Deptment>> for TreeItems {
    fn from(items: Vec<Deptment>) -> Self {
        let opts: Vec<TreeItem> = items
            .into_iter()
            .map(|item| TreeItem::new(item.id.to_string(), item.name, None, vec![], None))
            .collect();
        Self {
            items: opts,
            not_shows: RwSignal::new(vec![]),
        }
    }
}
fn add_menus(items: Vec<MenuItem>, pid: Option<String>, opts: &mut Vec<TreeItem>) -> Vec<String> {
    let mut ret_child: Vec<String> = Vec::new();
    items.into_iter().for_each(|c| {
        let id = c.id.to_string();
        // 首先创建菜单项（不包含权限信息）
        let menu_item = TreeItem::new(
            id.clone(),
            c.name,
            pid.clone(),
            vec![], // 初始为空，稍后添加子节点ID
            None,   // 菜单项本身不包含权限信息
        );
        // 保存菜单项在opts中的索引
        let menu_index = opts.len();
        opts.push(menu_item);
        // 如果菜单项有子菜单，则递归处理
        if !c.children.is_empty() {
            // 创建子菜单的副本以避免移动
            let child_items = c.children.clone();
            let children = add_menus(child_items, Some(id.clone()), opts);
            // 更新菜单项的子节点列表
            opts[menu_index].children = children;
        }
        // 如果菜单项有权限信息，则添加权限子节点
        if let Some(perm) = c.permission {
            let mut permission_children: Vec<String> = Vec::new();
            // 添加操作权限子节点
            if !perm.auth_types.is_empty() {
                let auth_id = format!("{}_auth", id);
                let auth_label = "操作权限".to_string();
                let auth_item =
                    TreeItem::new(auth_id.clone(), auth_label, Some(id.clone()), vec![], None);
                opts.push(auth_item);
                permission_children.push(auth_id);
            }
            // 添加行级权限子节点
            if !perm.row_ranges.is_empty() {
                let row_id = format!("{}_row", id);
                let row_label = "行级权限".to_string();
                let row_item =
                    TreeItem::new(row_id.clone(), row_label, Some(id.clone()), vec![], None);
                opts.push(row_item);
                permission_children.push(row_id);
            }
            // 添加列级权限子节点
            if !perm.column_ranges.is_empty() {
                let col_id = format!("{}_col", id);
                let col_label = "列级权限".to_string();
                let col_item =
                    TreeItem::new(col_id.clone(), col_label, Some(id.clone()), vec![], None);
                opts.push(col_item);
                permission_children.push(col_id);
            }
            // 更新菜单项的子节点列表，添加权限节点
            if !permission_children.is_empty() {
                // 如果菜单项已有子菜单，合并子菜单和权限节点
                if !c.children.is_empty() {
                    // 由于之前已经克隆了c.children，这里可以安全地使用
                    opts[menu_index].children.append(&mut permission_children);
                } else {
                    // 如果菜单项没有子菜单，直接设置为权限节点
                    opts[menu_index].children = permission_children;
                }
            }
            // 添加操作权限的具体类型
            for (_, auth_type) in perm.auth_types.iter().enumerate() {
                let at: u8 = auth_type.clone().into();
                let auth_type_id = format!("{}_auth_{}", id, at);
                let auth_type_label = auth_type.to_string();
                let auth_type_item = TreeItem::new(
                    auth_type_id.clone(),
                    auth_type_label,
                    Some(format!("{}_auth", id)),
                    vec![],
                    None,
                );
                opts.push(auth_type_item);
                // 更新操作权限节点的子节点列表
                let auth_index = opts
                    .iter()
                    .position(|item| item.id == format!("{}_auth", id))
                    .unwrap_or(0);
                opts[auth_index].children.push(auth_type_id);
            }
            // 添加行级权限的具体类型
            for (_, row_range) in perm.row_ranges.iter().enumerate() {
                let i: u8 = row_range.clone().into();
                let row_range_id = format!("{}_row_{}", id, i);
                let row_range_label = row_range.to_string();
                let row_range_item = TreeItem::new(
                    row_range_id.clone(),
                    row_range_label,
                    Some(format!("{}_row", id)),
                    vec![],
                    None,
                );
                opts.push(row_range_item);
                // 更新行级权限节点的子节点列表
                let row_index = opts
                    .iter()
                    .position(|item| item.id == format!("{}_row", id))
                    .unwrap_or(0);
                opts[row_index].children.push(row_range_id);
            }

            // 添加列级权限的具体类型
            for (_, column_range) in perm.column_ranges.iter().enumerate() {
                let i: u8 = column_range.clone().into();
                let column_range_id = format!("{}_col_{}", id, i);
                let column_range_label = column_range.to_string();
                let column_range_item = TreeItem::new(
                    column_range_id.clone(),
                    column_range_label,
                    Some(format!("{}_col", id)),
                    vec![],
                    None,
                );
                opts.push(column_range_item);
                // 更新列级权限节点的子节点列表
                let col_index = opts
                    .iter()
                    .position(|item| item.id == format!("{}_col", id))
                    .unwrap_or(0);
                opts[col_index].children.push(column_range_id);
            }
        }

        ret_child.push(id);
    });
    ret_child
}
fn add_cols(cols: &Vec<Column>, pid: Option<String>, opts: &mut Vec<TreeItem>) -> Vec<String> {
    let mut ret_child: Vec<String> = Vec::new();
    cols.iter().enumerate().for_each(|(i, c)| {
        let name = c.name.clone();
        let id = if let Some(name) = name {
            name
        } else {
            if let Some(pid) = &pid {
                format!("{pid}_{}", i)
            } else {
                format!("p_{}", i)
            }
        };
        if c.children.is_empty() {
            if let Some(title) = c.title.clone() {
                ret_child.push(id.clone());
                opts.push(TreeItem::new(id, title, pid.clone(), vec![], None));
            }
        } else {
            let children = add_cols(c.children.as_ref(), Some(id.clone()), opts);
            if let Some(title) = c.title.clone() {
                ret_child.push(id.clone());
                opts.push(TreeItem::new(id, title, pid.clone(), children, None));
            }
        }
    });
    ret_child
}
fn add_col_cells(
    cols: &Vec<ColumnCell>,
    pid: Option<String>,
    opts: &mut Vec<TreeItem>,
) -> Vec<String> {
    let mut ret_child: Vec<String> = Vec::new();
    cols.iter().enumerate().for_each(|(i, c)| match c {
        ColumnCell::Leaf(l) => {
            let name = l.name.clone();
            let title = l.title.clone();
            if let Some(title) = title {
                ret_child.push(name.clone());
                opts.push(TreeItem::new(name, title, pid.clone(), vec![], None));
            }
        }
        ColumnCell::Branch(b) => {
            if b.children.is_empty() {
                return;
            }
            let id = format!("{}_{}", pid.as_deref().unwrap_or("p"), i);
            let children = add_col_cells(b.children.as_ref(), Some(id.clone()), opts);
            ret_child.push(id.clone());
            opts.push(TreeItem::new(
                id,
                b.title.clone(),
                pid.clone(),
                children,
                None,
            ));
        }
        ColumnCell::None => {}
    });
    ret_child
}

#[derive(Clone, Default, PartialEq, Eq)]
pub enum ExpandMode {
    All,
    First,
    #[default]
    None,
}
#[derive(Debug, Clone, Default, Copy, PartialEq, Eq)]
pub enum CheckState {
    All,
    Any,
    #[default]
    None,
}
// 组件中使用一个扁平结构存储所有状态
#[derive(Debug)]
pub struct TreeState {
    items: HashMap<String, TreeItem>,
    pre_selected: RwSignal<Option<String>>,
    selected: RwSignal<Option<String>>,
    multi_selected: HashMap<String, RwSignal<CheckState>>,
    expanded: HashMap<String, RwSignal<bool>>,
    root_ids: Vec<String>,
    not_shows: ReadSignal<Vec<String>>,
}
impl TreeState {
    pub fn from_multi(
        tree_items: &TreeItems,
        init_vals: &Vec<String>,
        init_expand_mode: &ExpandMode,
    ) -> Self {
        let mut items: HashMap<String, TreeItem> = HashMap::new();
        let selected: RwSignal<Option<String>> = RwSignal::new(None);
        let mut multi_selected: HashMap<String, RwSignal<CheckState>> = HashMap::new();
        let mut expanded: HashMap<String, RwSignal<bool>> = HashMap::new();
        let mut sel_ids: Vec<&str> = Vec::new();
        let mut root_ids: Vec<String> = Vec::new();
        for item in tree_items.to_items() {
            let id = item.id.clone();
            if item.parent_id.is_none() || item.parent_id == Some("".to_string()) {
                root_ids.push(id.clone());
            }
            items.insert(id.clone(), item.clone());
            if item.children.is_empty() {
                let is_sel = init_vals.contains(&id);
                if is_sel {
                    sel_ids.push(&item.id);
                }
                let s = if is_sel {
                    CheckState::All
                } else {
                    CheckState::None
                };
                multi_selected.insert(id, RwSignal::new(s));
            } else {
                multi_selected.insert(id.clone(), RwSignal::new(CheckState::None));
                expanded.insert(
                    id,
                    RwSignal::new(match init_expand_mode {
                        ExpandMode::All => true,
                        ExpandMode::First => item.parent_id.is_none(),
                        ExpandMode::None => false,
                    }),
                );
            }
        }
        let not_shows = tree_items.not_shows.read_only();
        let ts = Self {
            items,
            pre_selected: RwSignal::new(None),
            selected,
            multi_selected,
            expanded,
            root_ids,
            not_shows,
        };
        for id in sel_ids {
            ts.update_parent_state(id);
        }
        ts
    }
    pub fn from_single(
        tree_items: &TreeItems,
        init_val: Option<String>,
        init_expand_mode: &ExpandMode,
    ) -> Self {
        let mut items: HashMap<String, TreeItem> = HashMap::new();
        let selected: RwSignal<Option<String>> = RwSignal::new(init_val);
        let mut expanded: HashMap<String, RwSignal<bool>> = HashMap::new();
        let mut root_ids: Vec<String> = Vec::new();
        for item in tree_items.to_items() {
            let id = item.id.clone();
            if item.parent_id.is_none() || item.parent_id == Some("".to_string()) {
                root_ids.push(id.clone());
            }
            items.insert(id.clone(), item.clone());
            if !item.children.is_empty() {
                expanded.insert(
                    id,
                    RwSignal::new(match init_expand_mode {
                        ExpandMode::All => true,
                        ExpandMode::First => item.parent_id.is_none(),
                        ExpandMode::None => false,
                    }),
                );
            }
        }
        let not_shows = tree_items.not_shows.read_only();
        Self {
            items,
            pre_selected: RwSignal::new(None),
            selected,
            multi_selected: HashMap::new(),
            expanded,
            root_ids,
            not_shows,
        }
    }
    fn from(
        tree_items: TreeItems,
        init_vals: &Vec<String>,
        init_val: Option<String>,
        init_expand_mode: &ExpandMode,
        is_multi: bool,
    ) -> Self {
        let mut items: HashMap<String, TreeItem> = HashMap::new();
        let selected: RwSignal<Option<String>> =
            RwSignal::new(if is_multi { None } else { init_val });
        let mut multi_selected: HashMap<String, RwSignal<CheckState>> = HashMap::new();
        let mut expanded: HashMap<String, RwSignal<bool>> = HashMap::new();
        let mut sel_ids: Vec<&str> = Vec::new();
        let mut root_ids: Vec<String> = Vec::new();
        for item in tree_items.to_items() {
            let id = item.id.clone();
            if item.parent_id.is_none() {
                root_ids.push(id.clone());
            }
            items.insert(id.clone(), item.clone());
            if item.children.is_empty() {
                let is_sel = init_vals.contains(&id);
                if is_sel {
                    sel_ids.push(&item.id);
                }
                let s = if is_sel {
                    CheckState::All
                } else {
                    CheckState::None
                };
                multi_selected.insert(id, RwSignal::new(s));
            } else {
                multi_selected.insert(id.clone(), RwSignal::new(CheckState::None));
                expanded.insert(
                    id,
                    RwSignal::new(match init_expand_mode {
                        ExpandMode::All => true,
                        ExpandMode::First => item.parent_id.is_none(),
                        ExpandMode::None => false,
                    }),
                );
            }
        }
        let not_shows = tree_items.not_shows.read_only();
        let ts = Self {
            items,
            pre_selected: RwSignal::new(None),
            selected,
            multi_selected,
            expanded,
            root_ids,
            not_shows,
        };
        for id in sel_ids {
            ts.update_parent_state(id);
        }
        ts
    }
    pub fn get_selected(&self) -> Option<String> {
        self.selected.get()
    }
    pub fn get_selected_values(&self) -> Vec<String> {
        self.items
            .iter()
            .filter(|(_, item)| item.is_leaf())
            .filter(|(id, _)| self.multi_selected[id.as_str()].get() == CheckState::All)
            .map(|(id, _)| id.clone())
            .collect()
    }
    pub fn get_multi_selected(&self, id: &str) -> Option<RwSignal<CheckState>> {
        self.multi_selected.get(id).map(|s| s.clone())
    }
    pub fn clear_multi_selected(&self) {
        for (_k, v) in self.multi_selected.as_borrowed() {
            v.set(CheckState::None);
        }
    }
    pub fn get_expanded(&self, id: &str) -> Option<RwSignal<bool>> {
        self.expanded.get(id).map(|s| s.clone())
    }
    pub fn set_selected(&self, id: Option<String>) {
        self.selected.set(id);
    }
    pub fn set_multi_selected(&self, id: &str, selected: bool) {
        self.multi_selected[id].set(if selected {
            CheckState::All
        } else {
            CheckState::None
        });
        if self.items[id].parent_id.is_some() {
            self.update_parent_state(id);
        }
        if !self.items[id].children.is_empty() {
            self.update_children_state(id, selected);
        }
    }
    pub fn set_expanded(&self, id: &str, expanded: bool) {
        self.expanded.get(id).map(|s| s.set(expanded));
    }
    pub fn get_root_ids(&self, filter_text: Option<&str>) -> Vec<String> {
        if let Some(ft) = filter_text {
            self.root_ids
                .iter()
                .filter(|id| self.is_filtered(id, ft))
                .cloned()
                .collect()
        } else {
            self.root_ids
                .iter()
                .filter(|id| {
                    !self
                        .not_shows
                        .with(|names| names.iter().any(|name| name == *id))
                })
                .cloned()
                .collect()
        }
    }
    pub fn get_item_ids_by_pid(&self, pid: &str, filter_text: Option<&str>) -> Vec<String> {
        let mut ids: Vec<String> = Vec::new();
        for id in self.items[pid].children.iter() {
            if let Some(ft) = filter_text {
                if self.is_filtered(id, ft) {
                    ids.push(id.clone());
                }
            } else {
                ids.push(id.clone());
            }
        }
        ids
    }
    fn is_filtered(&self, id: &str, filter_text: &str) -> bool {
        if self
            .not_shows
            .with(|names| names.iter().any(|name| name == id))
        {
            return false;
        }
        let is_ok = self.items[id].label.contains(filter_text);
        if self.items[id].is_leaf() {
            return is_ok;
        }
        self.items[id]
            .children
            .iter()
            .any(|cid| self.is_filtered(cid, filter_text))
            || is_ok
    }
    pub fn get_label(&self, id: &str) -> &str {
        self.items
            .get(id)
            .map(|item| item.get_label())
            .unwrap_or_default()
    }
    pub fn is_leaf(&self, id: &str) -> bool {
        self.items
            .get(id)
            .map(|item| item.is_leaf())
            .unwrap_or_default()
    }
    pub fn pre_select_prev(&self) {
        self.pre_selected.with_untracked(|id|{
            let id=if let Some(id)= id {
                self.find_prev_item_id(id).map(|v|v.to_owned())
            }else{
                None
            };
            self.pre_selected.set(id);
        });
    }
    pub fn pre_select_next(&self) {
        self.pre_selected.with_untracked(|id|{
            let id=if let Some(id)= id {
                self.find_next_item_id(id).map(|v|v.to_owned())
            }else{
                self.root_ids.get(0).map(|v|v.clone())
            };
            self.pre_selected.set(id);
        });
    }
    pub fn get_pre_selected(&self) -> RwSignal<Option<String>> {
        self.pre_selected
    }
    fn find_prev_item_id(&self, id: &str) -> Option<&str> {
        if let Some(idx) = self.root_ids.iter().position(|x| x == id) {
            if idx > 0 {
                return Some(&self.root_ids[idx - 1]);
            }
        } else {
            if let Some(ti) = self.items.get(id) {
                if let Some(pid) = &ti.parent_id {
                    if let Some(idx) = self.items[pid].children.iter().position(|x| x == id) {
                        if idx > 0 {
                            return Some(&self.items[pid].children[idx - 1]);
                        } else {
                            return Some(pid);
                        }
                    }
                }
            }
        }
        None
    }
    fn find_next_item_id(&self, id: &str) -> Option<&str> {
        if let Some(idx) = self.root_ids.iter().position(|x| x == id) {
            if idx < self.root_ids.len() - 1 {
                return Some(&self.root_ids[idx + 1]);
            }
        } else {
            if let Some(ti) = self.items.get(id) {
                if !ti.children.is_empty()&&self.expanded.contains_key(id) {
                    return Some(&ti.children[0]);
                }
                if let Some(pid) = &ti.parent_id {
                    if let Some(idx) = self.items[pid].children.iter().position(|x| x == id) {
                        if idx < self.items[pid].children.len() - 1 {
                            return Some(&self.items[pid].children[idx + 1]);
                        } else {
                            return self.find_next_item_id(pid);
                        }
                    }
                }
            }
        }
        None
    }
}

impl TreeState {
    // 在组件中添加联动更新函数
    fn update_parent_state(&self, item_id: &str) {
        let item = self.items.get(item_id).unwrap();
        if let Some(parent_id) = &item.parent_id {
            if parent_id.is_empty() {
                return; // 根节点没有父节点
            }
            let parent = self.items.get(parent_id).unwrap();
            let clen = parent.children.len();
            let mut all_count = 0_u16;
            let mut any_count = 0_u16;
            for cid in parent.children.iter() {
                let s = self.multi_selected[cid].get_untracked();
                if s == CheckState::Any {
                    any_count += 1;
                } else if s == CheckState::All {
                    all_count += 1;
                }
            }
            let p_st = if all_count == clen as u16 {
                CheckState::All
            } else if any_count > 0 || all_count > 0 {
                CheckState::Any
            } else {
                CheckState::None
            };
            // 更新父节点状态但不触发无限循环
            let parent_signal = self.multi_selected[parent_id];
            if parent_signal.get_untracked() != p_st {
                parent_signal.set(p_st);
                self.update_parent_state(parent_id); // 继续向上传播
            }
        }
    }
    // 同样为子节点实现联动
    fn update_children_state(&self, item_id: &str, selected: bool) {
        let item = self.items.get(item_id).unwrap();
        let state = if selected {
            CheckState::All
        } else {
            CheckState::None
        };
        self.multi_selected[item_id].set(state);
        for child_id in &item.children {
            self.update_children_state(child_id, selected); // 向下传播
        }
    }
}
